from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uuid
import json
from typing import Optional

app = FastAPI()

# 允许跨域请求
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


class ChatRequest(BaseModel):
    question: str
    conversationId: str
    stream: bool


# 预定义的响应数据
sample_response = {
    "code": "200",
    "msg": "操作成功！",
    "data": json.dumps({
        "id": f"chat-{str(uuid.uuid4())}",
        "object": "chat.completion",
        "created": 1753252091,
        "model": "Qwen2.5-728.Instru ct-JSPT",
        "choices": [{
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "这是对您问题的回答",
                "tool_calls": []
            },
            "logprobs": None,
            "finish_reason": "stop",
            "stop_reason": None
        }],
        "usage": {
            "prompt_tokens": 29,
            "total_tokens": 364,
            "completion_tokens": 335
        },
        "prompt_iogprobs": None
    })
}


@app.post("/api/v1/chatSream/getChatStreamAnswer")
async def get_chat_stream_answer(request: ChatRequest):
    try:
        # 可以根据 request.question 生成不同的回答
        response = sample_response.copy()

        # 替换回答内容为请求的问题的回应
        data_dict = json.loads(response["data"])
        data_dict["choices"][0]["message"]["content"] = f"这是对'{request.question}'的回答"
        response["data"] = json.dumps(data_dict)

        return response
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=3000)
